package com.srt.util.exception;

import com.srt.annotation.ResponseWithoutResult;
import com.srt.util.Result;
import com.srt.util.ResultUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * controller结果返回层的处理，根据注解统一转换成Result
 *
 * @name: MyResponseBodyAdvice
 * @author: rd07
 * @date: 2020/8/3
 * @time: 10:30
 */
@ConditionalOnProperty(prefix = "controller", name = "handler", havingValue = "true")
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Value("${controller.ignore-packages:springfox,org.springframework}")
    private List<String> ignorePkgs;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        // 忽略第3方包，如swagger, spring
        String pkg = methodParameter.getContainingClass().getPackage().getName();
        for (String ignorePkg : ignorePkgs) {
            if (pkg.startsWith(ignorePkg)) {
                return false;
            }
        }

        //获取当前处理请求的controller的方法
        ResponseWithoutResult responseWithoutResult =
                methodParameter.getMethod().getAnnotation(ResponseWithoutResult.class);
        return (responseWithoutResult == null);
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof Result) {
            return o;
        }
        return ResultUtils.getSuccess(o);
    }
}
